package com.ruoyi.web.controller.ora;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.KeyValidate;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.Builder;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ora.constant.BizConstants;
import com.ruoyi.ora.domain.DeviceAichat;
import com.ruoyi.ora.domain.VoiceTranModel;
import com.ruoyi.ora.factory.VoiceTranslatFactory;
import com.ruoyi.ora.service.IDeviceAichatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI聊天Controller
 * 
 * @author liuwp
 * @date 2025-08-22
 */
@RestController
@RequestMapping("/ora/device_aichat")
public class DeviceAichatController extends BaseController
{
    @Autowired
    private IDeviceAichatService deviceAichatService;

    /**
     * 查询AI聊天列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:list')")
    @GetMapping("/list")
    public TableDataInfo list(DeviceAichat deviceAichat)
    {
        startPage();
        List<DeviceAichat> list = deviceAichatService.selectDeviceAichatList(deviceAichat);
        return getDataTable(list);
    }

    /**
     * 导出AI聊天列表
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:export')")
    @Log(title = "AI聊天", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DeviceAichat deviceAichat)
    {
        List<DeviceAichat> list = deviceAichatService.selectDeviceAichatList(deviceAichat);
        ExcelUtil<DeviceAichat> util = new ExcelUtil<DeviceAichat>(DeviceAichat.class);
        util.exportExcel(response, list, "AI聊天数据");
    }

    /**
     * 获取AI聊天详细信息
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(deviceAichatService.selectDeviceAichatById(id));
    }

    /**
     * 新增AI聊天
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:add')")
    @Log(title = "AI聊天", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DeviceAichat deviceAichat)
    {
        return toAjax(deviceAichatService.insertDeviceAichat(deviceAichat));
    }

    /**
     * 修改AI聊天
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:edit')")
    @Log(title = "AI聊天", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DeviceAichat deviceAichat)
    {
        return toAjax(deviceAichatService.updateDeviceAichat(deviceAichat));
    }

    /**
     * 删除AI聊天
     */
    @PreAuthorize("@ss.hasPermi('ora:device_aichat:remove')")
    @Log(title = "AI聊天", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(deviceAichatService.deleteDeviceAichatByIds(ids));
    }

    /******设备相关********/
    @GetMapping("/query")
    @KeyValidate()
    public TableDataInfo deviceQuery(DeviceAichat deviceAichat)
    {
        if (StringUtils.isNotEmpty(deviceAichat.getDeviceSn())){
            startPage();
            List<DeviceAichat> list = deviceAichatService.selectDeviceAichatList(deviceAichat);
            return getDataTable(list);
        }
        return getDataTable(new ArrayList<>());
    }

    @PostMapping("/send")
    @KeyValidate()
    public AjaxResult deviceAdd(DeviceAichat deviceAichat, MultipartFile file)
    {
        if (file != null){
            try {
                String filePath = RuoYiConfig.getUploadPath();
                String fileName = FileUploadUtils.upload(filePath, file);
                deviceAichat.setDeviceVoice(fileName);
                deviceAichat.setChatType(1);    // 对话类型  1：设备toApp，2：aiTo设备
                // 把音频转写成文字
                VoiceTranModel voiceTranModel = VoiceTranslatFactory.build(BizConstants.TRAN_MODEL.getValue()).voiceTranslat(fileName.replace(Constants.RESOURCE_PREFIX, RuoYiConfig.getProfile()));
                if (voiceTranModel != null){
                    deviceAichat.setDeviceContent(voiceTranModel.getText());
                    deviceAichat.setDeviceDuration(voiceTranModel.getTotalDuration());
                    deviceAichatService.insertDeviceAichat(deviceAichat);
                    PageHelper.startPage(1,10, "id desc");
                    List<DeviceAichat> deviceAichats = deviceAichatService.selectDeviceAichatList(Builder.of(DeviceAichat::new)
                            .with(DeviceAichat::setDeviceSn, deviceAichat.getDeviceSn())
                            .build());
                    deviceAichats = deviceAichats.stream().sorted(Comparator.comparingLong(DeviceAichat::getId)).collect(Collectors.toList());
                    // 调用AI自动回复
                    DeviceAichat aichatReply = deviceAichatService.aichatAutoReply(deviceAichats);
                    if (aichatReply != null){
                        deviceAichatService.insertDeviceAichat(aichatReply);
                    }
                    return AjaxResult.success(aichatReply);
                }
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }else if (StringUtils.isNotEmpty(deviceAichat.getDeviceContent())){
//            deviceAichat.setDeviceContent(voiceTranModel.getText());
//            deviceAichat.setDeviceDuration(voiceTranModel.getTotalDuration());
            deviceAichat.setChatType(1);
            deviceAichatService.insertDeviceAichat(deviceAichat);
            PageHelper.startPage(1,10, "id desc");
            List<DeviceAichat> deviceAichats = deviceAichatService.selectDeviceAichatList(Builder.of(DeviceAichat::new)
                    .with(DeviceAichat::setDeviceSn, deviceAichat.getDeviceSn())
                    .build());
            deviceAichats = deviceAichats.stream().sorted(Comparator.comparingLong(DeviceAichat::getId)).collect(Collectors.toList());
            // 调用AI自动回复
            DeviceAichat aichatReply = deviceAichatService.aichatAutoReply(deviceAichats);
            if (aichatReply != null){
                deviceAichatService.insertDeviceAichat(aichatReply);
            }
            return AjaxResult.success(aichatReply);
        }
        return AjaxResult.error();
    }

    @PutMapping("/deviceEdit")
    @KeyValidate()
    public AjaxResult deviceEdit(DeviceAichat deviceAichat)
    {
        return toAjax(deviceAichatService.updateDeviceAichat(deviceAichat));
    }

    /******app相关********/
//    @GetMapping("/appQuery")
//    public TableDataInfo appQuery(DeviceAichat deviceAichat)
//    {
//        deviceAichat.setUserId(SecurityUtils.getUserId());
//        startPage();
//        List<DeviceAichat> list = deviceAichatService.selectDeviceAichatList(deviceAichat);
//        return getDataTable(list);
//    }

    // TODO 不对 这个是ai自动回的。。。 暂时注释掉
//    @PostMapping("/appAdd")
//    public AjaxResult userAdd(DeviceAichat deviceAichat, MultipartFile file)
//    {
//        if (file != null){
//            try {
//                String filePath = RuoYiConfig.getUploadPath();
//                String fileName = FileUploadUtils.upload(filePath, file);
//                deviceAichat.setAichatVoice(fileName);
//            }
//            catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        deviceAichat.setUserId(SecurityUtils.getUserId());
//        return toAjax(deviceAichatService.insertDeviceAichat(deviceAichat));
//    }
//
//    @PutMapping("/appEdit")
//    public AjaxResult appEdit(@RequestBody DeviceAichat deviceAichat)
//    {
//        return toAjax(deviceAichatService.updateDeviceAichat(deviceAichat));
//    }
}
